package com.kclm.xsap.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kclm.xsap.entity.*;
import com.kclm.xsap.service.*;
import com.kclm.xsap.utils.R;
import com.kclm.xsap.vo.BindCardInfoVo;
import com.kclm.xsap.vo.ConsumeFormVo;
import com.kclm.xsap.vo.OperateRecordVo;
import com.kclm.xsap.vo.ReserveFormCountVo;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;

/**
 * 会员卡管理控制器
 */
@Slf4j
@Controller
@RequestMapping("/card")
public class MemberCardController {
    private static String IGNORE = "version";
    @Autowired
    private MemberCardService memberCardService;
    @Autowired
    private RechargeRecordService rechargeRecordService;
    @Autowired
    private MemberBindRecordService memberBindRecordService;
    @Autowired
    private ConsumeRecordService consumeRecordService;
    @Autowired
    private CourseCardService courseCardService;
    @Autowired
    private ClassRecordService classRecordService;
    @Autowired
    private MemberLogService memberLogService;
    @Autowired
    private ScheduleRecordService scheduleRecordService;
    @Autowired
    private CourseService courseService;

    /**
     * 跳转
     */
    @GetMapping("/x_member_card.do")
    public String memberCard() {
        return "member/x_member_card";
    }

    /**
     * 遍历会员卡列表
     */
    @PostMapping("/cardList.do")
    @ResponseBody
    public R cardList() {
        List<MemberCardEntity> list = memberCardService.list(null);
        return R.ok("返回会员卡列表").put("data", list);
    }

    /**
     * 充值
     */
    @PostMapping("/rechargeOpt.do")
    @ResponseBody
    public R rechargeOpt(@Valid RechargeRecordEntity rechargeRecordEntity, BindingResult bindingResult) {
        //判断是否有值错误
        if (bindingResult.hasErrors()) {
            final List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            return R.error(400, "非法参数").put("error", fieldErrors);
        }
        boolean isInfo = memberCardService.isInfo(rechargeRecordEntity);
        if (isInfo) {
            return R.ok();
        } else {
            return R.error("充值失败请重试!");
        }
    }

    @PostMapping("/operateRecord.do")
    @ResponseBody
    public R operateRecord(Integer mememberId, Integer cardId) {
        //获取状态
        QueryWrapper<MemberBindRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id", cardId);
        MemberBindRecordEntity one = memberBindRecordService.getOne(wrapper);
        List<MemberLogEntity> memberLogEntities = memberLogService.list(new QueryWrapper<MemberLogEntity>().eq("member_bind_id", cardId));
        List<OperateRecordVo> operateRecordVos = new ArrayList<>();
        for (MemberLogEntity memberLogEntity : memberLogEntities) {
            OperateRecordVo operateRecordVo = new OperateRecordVo();
            operateRecordVo.setOperateTime(memberLogEntity.getCreateTime());
            operateRecordVo.setOperateType(memberLogEntity.getType());
            operateRecordVo.setChangeCount(memberLogEntity.getCardCountChange());
            operateRecordVo.setChangeMoney(String.valueOf(memberLogEntity.getInvolveMoney()));
            operateRecordVo.setOperator(memberLogEntity.getOperator());
            operateRecordVo.setCardNote(memberLogEntity.getNote());
            operateRecordVo.setStatus(memberLogEntity.getCardActiveStatus());
            operateRecordVos.add(operateRecordVo);
        }
        return R.ok().put("data", operateRecordVos);
    }

    @GetMapping("/x_member_add_card.do")
    public String memberAddCardTo() {

        return "member/x_member_add_card";
    }

    @PostMapping("/cardAdd.do")
    @ResponseBody
    public R cardAdd(@Valid MemberCardEntity memberCardEntity, BindingResult bindingResult, String courseListStr) {
        if (bindingResult.hasErrors()) {
            HashMap<String, String> errorMap = new HashMap<>();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return R.error(400, "非法参数").put("errorMap", errorMap);
        }
        List<String> list = new ArrayList<>();
        if (courseListStr != null) {
            list = Arrays.asList(courseListStr.split(","));
        }
        if (memberCardService.save(memberCardEntity)) {
            for (String s : list) {
                CourseCardEntity courseCardEntity = new CourseCardEntity();
                courseCardEntity.setCardId(memberCardEntity.getId());
                courseCardEntity.setCourseId(Long.valueOf(s));
                courseCardService.save(courseCardEntity);
            }
            return R.ok("添加成功").put("data", memberCardEntity);
        } else {
            return R.error("添加失败,请重试");
        }

    }

    @GetMapping("/x_member_card_edit.do")
    public String memberCardEditTo(Integer id, Model model) {
        MemberCardEntity memberCardEntity = memberCardService.getById(id);
        List<CourseCardEntity> courseCardEntityList = courseCardService.list(new QueryWrapper<CourseCardEntity>()
                .eq("card_id", id));
        List<Long> coruseIds = new ArrayList<>();
        for (CourseCardEntity courseCardEntity : courseCardEntityList) {
            coruseIds.add(courseCardEntity.getCourseId());
        }
        model.addAttribute("courseCarry", coruseIds);
        model.addAttribute("cardMsg", memberCardEntity);
        return "member/x_member_card_edit";
    }

    @PostMapping("/cardEdit.do")
    @ResponseBody
    public R cardEdit(@NonNull MemberCardEntity memberCardEntity, @RequestParam("courseListStr") String courseListStr
            , @RequestParam("timesCostList") String timesCostList) {
        System.out.println("=============================" + timesCostList);
        List<CourseCardEntity> courseCardEntityList = courseCardService.list(new QueryWrapper<CourseCardEntity>().eq("card_id", memberCardEntity.getId()));
        List<String> courseIds = new ArrayList<>();
        List<String> list = Arrays.asList(courseListStr.split(","));
        List<String> timesList = Arrays.asList(timesCostList.split(","));
        for (int i = 0; i < list.size(); i++) {
            CourseEntity courseEntity = courseService.getById(list.get(i));
            courseEntity.setTimesCost(Integer.valueOf(timesList.get(i)));
            courseService.updateById(courseEntity);
        }
        for (CourseCardEntity courseCardEntity : courseCardEntityList) {
            courseIds.add(String.valueOf(courseCardEntity.getCourseId()));
        }
        courseCardService.remove(new QueryWrapper<CourseCardEntity>().eq("card_id", memberCardEntity.getId()));
        for (String s : list) {
            CourseCardEntity courseCardEntity = new CourseCardEntity();
            courseCardEntity.setCardId(memberCardEntity.getId());
            courseCardEntity.setCourseId(Long.valueOf(s));
            courseCardService.save(courseCardEntity);
        }
        MemberCardEntity memberCardServiceById = memberCardService.getById(memberCardEntity);
        BeanUtils.copyProperties(memberCardEntity, memberCardServiceById, IGNORE);
        if (memberCardService.updateById(memberCardServiceById)) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @PostMapping("/deleteOne.do")
    @ResponseBody
    public R deleteCard(Integer id) {
        int courseBindCount = courseCardService.count(new QueryWrapper<CourseCardEntity>().eq("card_id", id));
        int memberBindCount = memberBindRecordService.count(new QueryWrapper<MemberBindRecordEntity>().eq("card_id", id));
        if (memberBindCount > 0) {
            return R.error("此卡已有会员绑定不能删除！");
        }
        if (courseBindCount > 0) {
            courseCardService.remove(new QueryWrapper<CourseCardEntity>().eq("card_id", id));
        }
        if (memberCardService.removeById(id)) {
            return R.ok().put("data", id);
        } else {
            return R.error("未知错误");
        }
    }

    /**
     * 扣费
     */
    @PostMapping("/consumeOpt.do")
    @ResponseBody
    public R consumeOpt(@Valid ConsumeFormVo consumeFormVo, BindingResult bindingResult) {
        System.out.println("consumeFormVo===========" + consumeFormVo);
        //return R.ok();
        if (bindingResult.hasErrors()) {
            HashMap<String, String> error = new HashMap<>();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                error.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return R.error(400, "非法参数").put("error", error);
        }
        ClassRecordEntity classRecordEntity = classRecordService.getOne(new QueryWrapper<ClassRecordEntity>()
                .eq("schedule_id", consumeFormVo.getScheduleId())
                .eq("member_id", consumeFormVo.getMemberId())
                .eq("bind_card_id", consumeFormVo.getCardBindId()));
        System.out.println("classRecordEntity====>" + classRecordEntity);

        if (classRecordEntity == null) {
            return R.error("该会员没有预约此课程");
        } else {
            boolean isConsum = memberCardService.consum(consumeFormVo);
            if (isConsum) {
                return R.ok();
            } else {
                return R.error("您的会员卡次数或金额不够，请充值！");
            }
        }
    }

    /**
     * 会员卡搜索，根据选择的会员
     */
    @PostMapping("/toSearchByMemberId.do")
    @ResponseBody
    public R toSearch(@RequestParam("memberId") Integer id) {
        System.out.println(id);
        List<MemberBindRecordEntity> memberBindRecordEntityList = memberBindRecordService.list(new QueryWrapper<MemberBindRecordEntity>()
                .eq("member_id", id)
                .eq("active_status", 1));
        List<BindCardInfoVo> bindCardInfoVoList = new ArrayList<>();
        for (MemberBindRecordEntity memberBindRecordEntity : memberBindRecordEntityList) {
            BindCardInfoVo bindCardInfoVo = new BindCardInfoVo();
            bindCardInfoVo.setId(memberBindRecordEntity.getId())
                    .setName(memberCardService.getById(memberBindRecordEntity.getCardId()).getName());
            bindCardInfoVoList.add(bindCardInfoVo);
        }
        return R.ok().put("value", bindCardInfoVoList);
    }

    /**
     * 显示某会员的某会员卡的提示信息
     */
    @PostMapping("/cardTip.do")
    @ResponseBody
    public R cardTip(@RequestParam("cardId") Integer cardId, @RequestParam("scheduleId") Integer scheduleId) {
        log.debug("前台传入的绑定id是{}", cardId);
        MemberBindRecordEntity bindEntityById = memberBindRecordService.getById(cardId);
        ScheduleRecordEntity scheduleWithCourseId = scheduleRecordService.getOne(new QueryWrapper<ScheduleRecordEntity>().eq("id", scheduleId));
        Long courseId = scheduleWithCourseId.getCourseId();
        CourseEntity courseEntity = courseService.getOne(new QueryWrapper<CourseEntity>().eq("id", courseId).select("times_cost"));
        ReserveFormCountVo reserveFormCountVo = new ReserveFormCountVo()
                .setCardTotalCount(bindEntityById.getValidCount())
                .setCardId(bindEntityById.getId())
                .setCardTotalDay(bindEntityById.getValidDay())
                .setCourseId(courseId)
                .setCourseTimesCost(courseEntity.getTimesCost());

        return R.ok().put("data", reserveFormCountVo);
    }

    /**
     * 卡状态变更
     */
    @PostMapping("/activeOpt.do")
    @ResponseBody
    public R activeOpt(@RequestParam("memberId") Long memberId,
                       @RequestParam("bindId") Long bindCardId,
                       @RequestParam("status") Integer status,
                       @RequestParam("operator") String operator) {
        System.out.println("会员id" + memberId);
        System.out.println("绑定id" + bindCardId);
        System.out.println("状态" + status);
        System.out.println("操作人" + operator);
        boolean isUpdate = memberBindRecordService.isUpdate(memberId, bindCardId, status, operator);
        if (isUpdate) {
            return R.ok().put("status", status);
        } else {
            return R.error();
        }
    }
}
